﻿/**
 * Copyright (C) 2012 original author and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGuice.Inject.Spi;

namespace NGuice.Inject.Internal
{
    /// <summary>
    /// 从module元素创建一个注入器的抽象基类。扩展类必须从所有重写的Visit*方法中返回true，以便元素处理器删除处理的元素
    /// </summary>
    public abstract class AbstractProcessor : DefaultElementVisitor<bool>
    {
        protected internal Errors errors;

        protected internal InjectorImpl injector;

        protected AbstractProcessor(Errors errors)
        {
            this.errors = errors;
        }

        public virtual void Process(IEnumerable<InjectorShell> isolatedInjectorBuilders)
        {
            foreach (InjectorShell injectorShell in isolatedInjectorBuilders)
            {
                Process(injectorShell.Injector, injectorShell.Elements);
            }
        }

        public virtual void Process(InjectorImpl injector, IList<IElement> elements)
        {
            Errors errorsAnyElement = this.errors;
            this.injector = injector;
            try
            {
                List<IElement> copy = new List<IElement>();
                copy.AddRange(elements);
                foreach (IElement element in copy)
                {
                    this.errors = errorsAnyElement.WithSource(element.Source);
                    bool allDone = element.AcceptVisitor(this);
                    if (allDone)
                    {
                        elements.Remove(element);//TODO:BUG?
                    }
                }
            }
            finally
            {
                this.errors = errorsAnyElement;
                this.injector = null;
            }
        }

        protected override bool VisitOther(IElement element)
        {
            return false;
        }
    }
}
